package cn.hchaojie.jd.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.hchaojie.jd.domain.Product;
import cn.hchaojie.jd.service.ProductService;

@Controller
public class ProductController {
	@Autowired
	ProductService service;
	
	@RequestMapping("home.action")
	public String home() {
		return "redirect:search.action?keyword=&category=&price=";
	}
	
	@RequestMapping("/search")
	public String search(
			@RequestParam(name = "keyword", defaultValue = "") String keyword,
			@RequestParam("category") String category,
			@RequestParam("price") String price,
			@RequestParam(name = "page", defaultValue = "0") Integer page,
			@RequestParam(name = "size", defaultValue = "10") Integer size,
			@RequestParam(name = "sort", defaultValue = "0") Integer s,		// 0或者1，0表示升序，1表示降序
			Model model) {
		
		Sort sort = Sort.by("price");
		sort = (s == 0) ? sort.ascending() : sort.descending();
		PageRequest pageable = PageRequest.of(page, size, sort);
		
		
		Page<Product> pageData = service.search(keyword, category, price, pageable);
		model.addAttribute("pageData", pageData);
		
		// 参数的回显
		if (!StringUtils.isEmpty(keyword)) {
			model.addAttribute("keyword", keyword);
		}
		if (!StringUtils.isEmpty(category)) {
			model.addAttribute("category", category);
		}
		if (!StringUtils.isEmpty(price)) {
			model.addAttribute("price", price);
		}
		if (!StringUtils.isEmpty(sort)) {
			model.addAttribute("sort", s);
		}

		return "product_list";
	}
}
